<template>
	<div>
		<Tabs>
			<TabPane label="编辑限时抢购"></TabPane>
		</Tabs>
		
		<Form ref="form" :model="formData" :rules="rules" label-position="top">
			<FormDescItem label="活动名称" prop="title" desc="给限时抢购活动定一个名称，多个活动名称不可重复，建议不超过20个字">
				<Input v-model="formData.title" />
			</FormDescItem>
			<FormDescItem label="有效期设置" prop="times" desc="请选择限时抢购活动生效日期及到期日期">
				<DatePicker v-model="formData.times" type="datetimerange" placeholder="请选择日期"></DatePicker>
			</FormDescItem>
			<FormDescItem label="商品限购" desc="设置商品限购数量，0为不限购">
				<Input v-model="formData.limit" number :disabled="formData.limit_disabled">
			        <template slot="append">
						<Checkbox label="不限购" v-model="formData.limit_disabled">不限购</Checkbox>
					</template>
			    </Input>
			</FormDescItem>
		</Form>
		
		<Divider />
		<div>
			<Button type="primary" @click="showGoodsModal = true">设置商品</Button>
		</div>
		<div v-if="selectedGoods.length > 0" style="margin-top: 15px;">
			<Table
		    	ref="table"
		    	:data="selectedGoods"
		    	:columns="columns"
		    >
		    	<div class="ui-table-cell ui-flex" slot-scope="{ row }" slot="goods">
		    		<ImageCell :src="row.thumb"></ImageCell>
		            <div class="ui-flex-full" style="margin-left: 10px;">
		            	<p class="ui-ellipsis2">{{ row.sku_name }}</p>
		            	<p class="ui-ellipsis ui-text-primary">{{ handleGetSpecTexts(row) }}</p>
		            </div>
		        </div>
		        <div slot-scope="{ row }" slot="price">
		        	<ui-price :value="row.shop_price"></ui-price>
		        </div>
		        <div slot-scope="{ row, index }" slot="promote_price">
		        	<InputNumber :value="row.promote_price" :min="0" :precision="2" style="width: 150px;" @on-change="handleChangePirce(index, $event)"></InputNumber>
		        </div>
		        <div slot-scope="{ row }" slot="action">
		        	<Button type="error" size="small" @click="handleDelete(row.sku_id)">删除</Button>
		        </div>
		    </Table>
		</div>
		
		<SelectGoods ref="goodsModal" v-model="showGoodsModal" :selected-data="selectedGoods" @on-change="handleChangeGoods"></SelectGoods>
		
		<LoadingMask v-if="loading"></LoadingMask>
		
		<FooterBar>
			<div style="text-align: center;">
				<Button @click="handleBack">返回列表</Button>
				<Button type="primary" @click="handleSubmit" :loading="commiting">保存设置</Button>
			</div>
		</FooterBar>
	</div>
</template>

<script>
import Util from '@/libs/util.js';
import Tools from '@/libs/tools.js';
import FooterBar from '@/components/FooterBar.vue';
import FormDescItem from '@/components/form/FormDescItem.vue';
import SelectGoods from '@/components/SelectGoods.vue';
import ImageCell from '@/components/ImageCell/index.vue';
import LoadingMask from '@/components/LoadingMask.vue';
export default {
	name: 'couponEdit',
	components: {
		FooterBar,
		FormDescItem,
		SelectGoods,
		ImageCell,
		LoadingMask
	},
	data() {
		return {
			loading: false,
			commiting: false,
			showGoodsModal: false,
			selectedGoods: [],
			formData: {
				id: null,
				title: '',
				times: [],
				limit: 0,
				limit_disabled: false,
				sku_info: []
			},
			rules: {
				title: [
					{required: true, message: '请输入优惠券名称', trigger: 'blur'}
				],
				times: [
					{required: true, type: 'array', message: '请选择有效期', trigger: 'change'}
				]
			},
			columns: [
                {
                    title: '商品',
                    slot: 'goods'
                },
                {
                    title: '价格',
                    slot: 'price',
                    width: 120
                },
                {
                    title: '库存',
                    key: 'number',
                    width: 120
                },
                {
                    title: '促销价',
                    slot: 'promote_price',
                    width: 186
                },
                {
                    title: '操作',
                    slot: 'action',
                    align: 'center',
                    width: 80
                }
			]
		}
	},
	mounted() {
		if(this.$route.query.id) {
    		this.formData.id = this.$route.query.id;
    		this.init();
    	}
	},
	methods: {
		init() {
			this.loading = true;
			Util.ajax.post(this.API['ADDONS_PROMOTION_TIME_DETAIL'], {id: this.formData.id}).then(res => {
				this.loading = false;
				this.formData.title = res.title;
				this.formData.times = [res.start_time * 1000, res.end_time * 1000];
				this.formData.limit = Number(res.limit) || 0;
				
				// 订单使用门槛为0时，表示无门槛
				if(this.formData.limit <= 0) {
					this.formData.limit_disabled = true;
				}
				
				this.selectedGoods = res.sku_info.map(item => {
					item.promote_price = Number(item.price);
					return item;
				});
				
			}).catch(() => {
				
			})
		},
		// 选择的商品
		handleChangeGoods(rows) {
			this.selectedGoods = rows.map(item => {
				if(!item.promote_price) {
					item.promote_price = 0.1;
				}
				return item;
			});
		},
		// 格式化规格数据
		handleGetSpecTexts(row) {
			if(!row.spec) return '';
			if(Array.isArray(row.spec)) {
				let texts = row.spec.map(item => {
					return item.name +':'+ item.value;
				})
				return texts.join('、');
			}else{
				return row.spec.name +':'+ row.spec.value;
			}
		},
		// 删除商品
		handleDelete(id) {
			this.selectedGoods = this.selectedGoods.filter(item => {
				return item.sku_id != id;
			})
		},
		// 改变促销价格
		handleChangePirce(index, value) {
			this.selectedGoods[index].promote_price = value;
		},
		// 返回上一级
		handleBack() {
			this.$router.back();
		},
		// 提交
		handleSubmit() {
			if(this.commiting) return false;
			this.$refs.form.validate((valid) => {
                if (valid) {
                	
                	if(this.selectedGoods.length == 0) {
                		this.$Message.error('请选择要参与活动的商品');
                		return false;
                	}
                	
                	let form = this.formData;
                    let params = {
                    	title: form.title,
                    	//start_time: Date.parse(new Date(form.times[0])) / 1000,
                    	//end_time: Date.parse(new Date(form.times[1])) / 1000,
                    	start_time: Tools.formatDate(form.times[0], 'yyyy-MM-dd hh:mm:ss'),
                    	end_time: Tools.formatDate(form.times[1], 'yyyy-MM-dd hh:mm:ss'),
                    	limit: (form.limit_disabled ? 0 : form.limit),
                    	sku_info: this.selectedGoods.map(item => {
                    		return {
                    			sku_id: item.sku_id,
                    			price: item.promote_price
                    		}
                    	})
                    }
                    
                    this.commiting = true;
                    if(form.id) {
                    	params.id = form.id;
                    	Util.ajax.post(this.API['ADDONS_PROMOTION_TIME_EDIT'], params).then((res) => {
	                    	this.commiting = false;
	                    	this.$Message.success({
	                    		content: '编辑成功',
	                    		onClose: () => {
	                    			this.handleBack();
	                    		}
	                    	})
	                    }).catch(() => {
	                    	this.commiting = false;
	                    })
                    }else{
                    	Util.ajax.post(this.API['ADDONS_PROMOTION_TIME_CREATE'], params).then((res) => {
	                    	this.commiting = false;
	                    	this.$Message.success({
	                    		content: '添加成功',
	                    		onClose: () => {
	                    			this.handleBack();
	                    		}
	                    	})
	                    }).catch(() => {
	                    	this.commiting = false;
	                    })
                    }
                }
            })
		}
	}
}
</script>